<template>
    <div class="page">
        <NavigationBar class="navigation-bar" :title="titleRef" @back="onBack">
            <template #right>
                <div style="font-size: 13rem;padding: 12rem;" @click="onSave">
                    确定
                </div>
            </template>
        </NavigationBar>
        <div class="container">
            <div class="field-card" style="margin-top: 12rem;">
                <div class="required-field" style="font-size: 14rem;">营地名</div>
                <el-input style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.camp_name" placeholder="请输入营地名称" maxlength="20" show-word-limit></el-input>
            </div>

            <div class="field-card">
                <div class="required-field" style="font-size: 14rem;">地区</div>
                <el-cascader
                  ref="districtSelectRef"
                  :placeholder="districtSelectDefault"
                  :props="districtSelectProps"
                  filterable
                />
            </div>

            <div class="field-card">
                <div class="required-field" style="font-size: 14rem;display: flex;align-items: center;">
                    <span style="flex: 1;">营地地址</span>
                    <div  style="display: inline-flex;align-items: center;"
                    @click="onShowSelectLocation">
                        <span style="font-size: 13rem;color: #AF8B6C;">点击定位</span>
                        <img style="width: 20rem; height: 20rem;" src="@/assets/ic_location.png">
                    </div>
                </div>
                <div v-if="editInfo.latitude&&editInfo.longitude">
                    <el-input  style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.location_addr"></el-input>
                </div>
            </div>

            <div class="field-card">
                <div class="required-field" style="font-size: 14rem;">营地图片</div>
                <draggable 
                  v-model="editInfoPictures" 
                  draggable=".edit-info-picture-item"
                  item-key="index"
                  style="display: flex;flex-wrap: wrap;width: 100%;margin-top: 10rem;"
                  >
                  <template #item="{element}">
                    <div v-if="element.type == 'button'" class="edit-info-picture-item-box" style="border-radius: 20px;border: 1px dashed #ccc;display: flex;justify-content: center; align-items: center;">
                      <el-upload
                        style="width: 100%; height: 100%;"
                        :show-file-list="false"
                        :auto-upload="false"
                        :multiple="true"
                        accept="image/*"
                        :on-change="onPictureSelect"
                        >
                        <div class="edit-info-picture-item-box" style="display: flex;justify-content: center; align-items: center;">
                          <el-icon size="20rem">
                            <Plus />
                          </el-icon>
                        </div>
                      </el-upload>
                    </div>
                    <div v-else class="edit-info-picture-item-box" style="position: relative;">
                      <img v-if="element.url" style="width: 100%; height: 100%;" :src="IMAGE_BASE_URL + element.url">
                      <img v-else-if="element.fileUrl" style="width: 100%; height: 100%;" :src="element.fileUrl">
                      <div v-else>错误</div>
                      <el-icon size="15rem" style="position:absolute;top: 10px; right: 10px;" @click="onPictureDelete(element)">
                        <Delete />
                      </el-icon>
                    </div>
                  </template>
                </draggable>
            </div>

            <div class="field-card">
                <div class="required-field" style="font-size: 14rem;">营地介绍</div>
                <el-input style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.content_intro" placeholder="请输入营地介绍"></el-input>
            </div>

            <div class="field-card">
                <div class="required-field" style="font-size: 14rem;">营地详情</div>
                <div style="border: 1px solid #ccc;margin-top: 10rem;">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 320px; overflow-y: hidden;font-size: 13rem;"
                    v-model="valueHtml"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                  />
                </div>
            </div>

            <div class="field-card">
                <div style="font-size: 14rem;">营地条件</div>
                <el-tree style="margin-top: 12rem;" 
                ref="treeRef" node-key="id" :default-expand-all="false" :data="conditionList" :props="conditionProps" show-checkbox></el-tree>
            </div>

            <div class="field-card">
                <div style="font-size: 14rem;">电话</div>
                <el-input style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.telephone" placeholder="请输入电话"></el-input>
            </div>

            <div class="field-card">
                <div style="font-size: 14rem;">手机</div>
                <el-input style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.cellphone" placeholder="请输入手机"></el-input>
            </div>

            <div class="field-card">
                <div style="font-size: 14rem;">微信</div>
                <el-input style="margin-top: 12rem;height: 40rem;font-size: 13rem;" v-model="editInfo.wechat" placeholder="请输入微信"></el-input>
            </div>
            
        </div>

        <el-dialog v-model="amapDialogVisible" title="选择定位" style="width: 90vw;">
          <div  style="height: 60vw;">
            <div>经度{{amapDialogSelect.lng}}: 纬度{{ amapDialogSelect.lat}},{{ amapDialogSelect.address }}</div>
            <SelectLocationInMap :lng="parseFloat(editInfo.longitude)" :lat="parseFloat(editInfo.latitude)" @select="onSelectLocation"/>
          </div>
          <template #footer>
            <div style="flex: 1;">
              <el-button type="primary" @click="onSaveLocation">确 定</el-button>
            </div>
          </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'CampUpload',
}
</script>

<script setup>
import flexible from "@/utils/amfeFlexible/index.js";
import NavigationBar from "@/components/navigationBar/NavigationBar.vue";
import { onMounted, onUnmounted, onBeforeUnmount, watch, ref, shallowRef } from "vue";
import SelectLocationInMap from "@/components/SelectLocationInMap.vue";
import draggable from 'vuedraggable'
import {IMAGE_BASE_URL, statusOptions, formatStatus} from "@/common/const";
import { ElMessage } from "element-plus"
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getFileMd5 } from "@/utils/md5"
import { 
  getDistrictTreePartial, 
} from '@/api/district'
import {
  uploadPicture
} from '@/api/upload'
import { 
  getConditionTree, 
} from '@/api/condition'

import { 
    createCamp,
} from '@/api/camp'
import { useRouter, useRoute } from 'vue-router'


flexible(window, document, 375)

const route = useRoute()

const editInfo = ref({
    status : 2
})
const amapDialogVisible = ref(false)
const amapDialogSelect = ref({})
const editInfoPictures = ref([
    {
      index: -1,
      type: "button"
    }
])

const districtSelectRef = ref(null);
const districtSelectDefault = ref("请选择地区");
const districtSelectProps = {
  multiple: false,
  checkStrictly: true,
  label: "name",
  value: "ad_code",
  lazy: true,
  async lazyLoad(node, resolve) {
    let adcode = ""
    if (node.value){
      adcode = node.value
      if(node.data.deep > 0){
        resolve([])
        return
      }
    }
    const res = await getDistrictTreePartial({ ad_code : adcode})
    if (res.data.tree.children){
      resolve(res.data.tree.children)
    } else {
      resolve([])
    }
  },
}


//条件分类
const conditionList = ref([])
const conditionProps = {
  children: 'children',
  label: 'name',
}
const treeRef = ref(null);


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref("")
const mode = 'default'
const toolbarConfig = {}
const editorConfig = { 
  placeholder: '请输入内容...',
  MENU_CONF: {}
}
editorConfig.MENU_CONF['uploadImage'] = {
    // 自定义上传
    async customUpload(file, insertFn) {
      let fd = new FormData()
      fd.append('file', file)
      const res = await uploadPicture(fd, route.query)
      insertFn(IMAGE_BASE_URL + res.data.url, "", res.data.url)
    }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}



onMounted(() => {
    console.log('onMounted');
    if (window.WebViewJavascriptBridge) {
        onJsBridgeReady()
    } else {
        document.addEventListener(
            'WebViewJavascriptBridgeReady'
            , function() {
                onJsBridgeReady()
            },
            false
        );
    }
})

function onJsBridgeReady() {
    console.log('onJsBridgeReady');
    if (window.WebViewJavascriptBridge) {
        window.WebViewJavascriptBridge.init(function(message, responseCallback) {
            console.log('native call', message);
            responseCallback(JSON.stringify({
                code : 0,
            }));
        });
    }
}

const titleRef = ref("基本信息")
function onBack() {
    if (window.WebViewJavascriptBridge) {
        window.WebViewJavascriptBridge.send(JSON.stringify({
            method : "closeWeb",
        }), function(responseData) {
            console.log("closeWeb back:", JSON.parse(responseData))
        })
    }
}


const onShowSelectLocation = async() => {
  amapDialogVisible.value = true
}

const onSelectLocation = async(position) => {
  amapDialogSelect.value.lng = position.lng
  amapDialogSelect.value.lat = position.lat
  amapDialogSelect.value.address = position.address
}

const onSaveLocation = async() => {
  editInfo.value.longitude = amapDialogSelect.value.lng.toString()
  editInfo.value.latitude = amapDialogSelect.value.lat.toString()
  editInfo.value.location_addr = amapDialogSelect.value.address
  amapDialogVisible.value = false
}

const onPictureSelect = (uploadFile, uploadFiles) => {
  let position = editInfoPictures.value.length - 1
  editInfoPictures.value.splice(position, 0,
    {
      index: position,
      file: uploadFile.raw,
      fileUrl: URL.createObjectURL(uploadFile.raw),
      url:'',
      width:0,
      height:0,
      type: "picture",
    }
  )
}

const onPictureDelete = (element) => {
  editInfoPictures.value.splice(editInfoPictures.value.indexOf(element), 1)
}


const onSave = async() => {

    if (districtSelectRef.value.getCheckedNodes(false).length > 0){
        let selected = districtSelectRef.value.getCheckedNodes(false)[0]
        editInfo.value.district_id = selected.value
        editInfo.value.district_name = selected.label
    }

    const selectedConditions = treeRef.value.getCheckedNodes(false, true)
    var conditiionMap = new Map()
    var conditiionMiss = []
    var conditionTree = {
    condition_id : 0,
    children : []
    }
    for (let index = 0; index < selectedConditions.length; index++) {
    const element = selectedConditions[index];
    conditiionMap.set(element.id, {
        condition_id : element.id,
        children : []
    })

    if(element.parent_id == 0){
        if(conditiionMap.has(element.id)){
        conditionTree.children.push(conditiionMap.get(element.id))
        }
    } else {
        if(conditiionMap.has(element.parent_id)){
        conditiionMap.get(element.parent_id).children.push(conditiionMap.get(element.id))
        } else {
        conditiionMiss.push(element)
        }
    }
    }
    if (conditiionMiss.length > 0) {
    console.log("wyq conditiionMiss", conditiionMiss)
    for (let index = 0; index < conditiionMiss.length; index++) {
        const element = selectedConditions[index];
        conditiionMap.get(element.parent_id).children.push(conditiionMap.get(element.id))
    }
    }
    editInfo.value.req_conditions = conditionTree.children


    var uploadReqList = []
    var uploadResultMap = new Map()
    for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    if(element.type === 'picture' && element.file) {
        let md5 = await getFileMd5(element.file)
        uploadResultMap.set(md5, element)
        let fd = new FormData()
        fd.append('file', element.file)
        uploadReqList.push(uploadPicture(fd,route.query))
    }
    }

    if(uploadReqList.length > 0){
    let uploadResult = await Promise.all(uploadReqList)
    .catch(error => console.error(error));
    for (let index = 0; index < uploadResult.length; index++) {
        const element = uploadResult[index];
        const item = uploadResultMap.get(element.data.md5)
        item.url = element.data.url
        item.width = element.data.width
        item.height = element.data.height
    }
    }

    var pictures = []
    for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    if(element.type === 'picture') {
        pictures.push({
        url: element.url,
        width: element.width,
        height: element.height
        })
    }
    }
    editInfo.value.req_images = pictures

    editInfo.value.content = valueHtml.value
    editInfo.value.content_json = JSON.stringify(editorRef.value.children)

    var res = await createCamp(editInfo.value, route.query)
    if(res.code === 0){
        ElMessage({
            type: 'success',
            message: "操作成功",
            showClose: true
        })
        onBack()
    } else {
        ElMessage({
            type: 'error',
            message: `${res.msg}`,
            showClose: true
        })
    }

}



const getConditionListData = async() => {
  try {
        const res = await getConditionTree({tree_id: 0})
        if(res.code === 0){
            conditionList.value = res.data.children
        } else {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
                showClose: true
            })
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: `${error}`,
            showClose: true
        })
    }
}



getConditionListData()



</script>

<style lang="scss" scoped>
.edit-info-picture-item-box{
  width: 20vw;
  height: 20vw;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}
</style>

<style lang="scss">

.page {
    background-color: #F6F6F6;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.navigation-bar {
    width: 100%;
    height: 54rem;
}

.container {
    position: relative;
    width: 100%;
    height: auto;
    flex: 1;
    overflow: scroll;
}

.field-card{
    background-color: white;
    margin: 0rem 12rem 12rem 12rem;
    border-radius: 10rem;
    padding: 10rem;
    .el-input__wrapper{
        --el-input-bg-color: #F6F6F6;
        --el-input-border-color: #F6F6F6;
        --el-fill-color-blank: #F6F6F6;
        .el-input__inner{
            height: 40rem;
        }
    }
    .el-input__count{
        font-size: 10rem;
    }
}

.el-cascader {
    width: 100%;
    .el-input__wrapper{
        --el-input-height: 40rem;
        font-size: 13rem;
    }
    .el-input .icon-arrow-down{
        font-size: 13rem;
    }
    
}
.el-cascader-panel{
    font-size: 13rem;
    .el-cascader-menu{
        min-width: 30vw;
    }
    .el-cascader-menu__empty-text .is-loading{
        font-size: 13rem !important;
    }
    .el-cascader-node {
        height: 20rem;
        font-size: 13rem;
        .el-radio__inner{
            width: 10rem;
            height: 10rem;
        }
    }
}

.el-tree-node{
    
    font-size: 13rem;
    .el-tree-node__content{
        height: 15rem;
        .el-tree-node__expand-icon{
            font-size: 13rem;
        }
        .el-checkbox__inner{
            width: 13rem;
            height: 13rem;
        }
        .el-checkbox__inner::before{
            height: 3rem;
            top: 5rem;
        }
        .el-checkbox__inner::after{
            width: 3rem;
            height: 7rem;
            border-width: 2rem;
            left: 4rem;
        }
    }
}


</style>